/**
 * Toast notification store
 *
 * Usage:
 * import { toast } from '../stores/toast';
 *
 * toast.success('Operation successful!');
 * toast.error('Operation failed', 5000);
 */

import { writable } from 'svelte/store';

export const toasts = writable([]);

let toastId = 0;

/**
 * Add a toast notification
 * @param {object} options - Toast options
 * @param {'success'|'error'|'warning'|'info'} options.type - Toast type
 * @param {string} options.message - Toast message
 * @param {number} options.duration - Duration in milliseconds (0 = manual close)
 * @returns {number} - Toast ID
 */
export function addToast({ type = 'info', message, duration = 3000 }) {
  const id = toastId++;
  toasts.update((all) => [...all, { id, type, message, duration }]);

  if (duration > 0) {
    setTimeout(() => removeToast(id), duration);
  }

  return id;
}

/**
 * Remove a toast by ID
 * @param {number} id - Toast ID
 */
export function removeToast(id) {
  toasts.update((all) => all.filter((t) => t.id !== id));
}

/**
 * Clear all toasts
 */
export function clearToasts() {
  toasts.set([]);
}

/**
 * Convenience methods for different toast types
 */
export const toast = {
  /**
   * Show success toast
   * @param {string} message - Success message
   * @param {number} [duration=3000] - Duration in milliseconds
   */
  success: (message, duration = 3000) => addToast({ type: 'success', message, duration }),

  /**
   * Show error toast
   * @param {string} message - Error message
   * @param {number} [duration=5000] - Duration in milliseconds
   */
  error: (message, duration = 5000) => addToast({ type: 'error', message, duration }),

  /**
   * Show warning toast
   * @param {string} message - Warning message
   * @param {number} [duration=4000] - Duration in milliseconds
   */
  warning: (message, duration = 4000) => addToast({ type: 'warning', message, duration }),

  /**
   * Show info toast
   * @param {string} message - Info message
   * @param {number} [duration=3000] - Duration in milliseconds
   */
  info: (message, duration = 3000) => addToast({ type: 'info', message, duration }),
};
